// usePipeDrawing.ts
import { onUnmounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import {
  Cartesian2,
  Cartesian3,
  Cartographic,
  Color,
  ConstantPositionProperty,
  Entity,
  LabelStyle,
  Math as CesiumMath,
  ScreenSpaceEventHandler,
  ScreenSpaceEventType,
  VerticalOrigin,
  HorizontalOrigin,
  Viewer
} from 'cesium';

export interface PipePoint {
  longitude: number;
  latitude: number;
  height?: number;
}

export interface PipeMaterial {
  material: string;
  diameter: number;
  pressure: number;
  thickness: number;
  coating: string;
}

export interface PipeData {
  points: PipePoint[];
  material: PipeMaterial;
  id?: string;
  type?: string; // 管线类型名称
}

// 风险数据接口
export interface PipeRiskInfo {
  level: string;
  value: number;
  rqzs: number;
  dsfsh: number;
  qtys: number;
  czjy: string;
}

interface PipeDrawingOptions {
  viewer: Ref<Viewer | null>;
  onPointAdded?: (points: PipePoint[]) => void;
  onDrawingComplete?: (pipeData: PipeData) => void;
  getUserDrawnPipe?: () => PipeData | null;
}

import { getDicts } from '@/api/system/dict/data';

// 风险等级字典
const riskLevelMap = ref<Record<string, string>>({});

// 初始化风险等级字典
const initRiskLevelDict = async () => {
  try {
    const { data } = await getDicts('grade_type');
    const map = {};
    data.forEach((item) => {
      map[item.dictValue] = item.dictLabel;
    });
    riskLevelMap.value = map;
  } catch (error) {
    console.error('获取风险等级字典失败:', error);
  }
};

// 格式化风险等级
const formatRiskLevel = (level: string) => {
  return riskLevelMap.value[level] || level;
};

const usePipeDrawing = (options: PipeDrawingOptions) => {
  const { viewer: viewerRef, onPointAdded, onDrawingComplete, getUserDrawnPipe } = options;

  const isDrawing = ref(false);
  const currentPoints = ref<PipePoint[]>([]);
  const currentPointEntities = ref<Entity[]>([]);
  const drawingEntity = ref<Entity | null>(null);
  const handler = ref<ScreenSpaceEventHandler | null>(null);

  // 开始绘制
  const startDrawing = () => {
    const viewer = viewerRef.value;
    // 检查 viewer 是否已初始化
    if (!viewer || !viewer.scene || !viewer.scene.canvas) {
      console.error('viewer 未初始化完成');
      ElMessage.error('地图未初始化完成，请稍后再试');
      return;
    }

    isDrawing.value = true;
    currentPoints.value = [];

    // 清除之前的点实体
    currentPointEntities.value.forEach((entity) => {
      viewer.entities.remove(entity);
    });
    currentPointEntities.value = [];

    // 创建事件处理器
    handler.value = new ScreenSpaceEventHandler(viewer.scene.canvas);

    handler.value.setInputAction((event: any) => {
      if (!isDrawing.value) {
        return;
      }

      // 使用 pickPosition 获取点击位置
      const position = viewer.scene.pickPosition(event.position);
      if (!position) {
        return;
      }

      // 转换为经纬度坐标
      const cartographic = Cartographic.fromCartesian(position);
      const point = {
        longitude: CesiumMath.toDegrees(cartographic.longitude),
        latitude: CesiumMath.toDegrees(cartographic.latitude),
        height: cartographic.height
      };

      addPoint(point);
    }, ScreenSpaceEventType.LEFT_CLICK);
  };

  // 添加点
  const addPoint = (point: PipePoint) => {
    const viewer = viewerRef.value;
    if (!viewer) {
      console.error('viewer 不可用');
      return;
    }

    currentPoints.value.push(point);

    // 通知外部点数变化
    if (onPointAdded) {
      onPointAdded([...currentPoints.value]);
    }

    // 添加点标记
    const pointEntity = viewer.entities.add({
      position: Cartesian3.fromDegrees(point.longitude, point.latitude, point.height || 0),
      point: {
        pixelSize: 8,
        color: Color.YELLOW,
        outlineColor: Color.BLACK,
        outlineWidth: 2
      }
    });

    // 保存点实体引用
    currentPointEntities.value.push(pointEntity);

    // 如果有两个或更多点，绘制线段
    if (currentPoints.value.length >= 2) {
      drawPolyline();
    }
  };

  // 绘制管线线段
  const drawPolyline = () => {
    const viewer = viewerRef.value;
    if (!viewer) {
      console.error('viewer 不可用');
      return;
    }

    if (drawingEntity.value) {
      viewer.entities.remove(drawingEntity.value);
    }

    const positions = currentPoints.value.map((point) => Cartesian3.fromDegrees(point.longitude, point.latitude, point.height || 0));

    drawingEntity.value = viewer.entities.add({
      polyline: {
        positions: positions,
        width: 4,
        material: Color.CYAN,
        clampToGround: true
      }
    });
  };

  // 完成绘制
  const finishDrawing = (): PipeData | null => {
    const viewer = viewerRef.value;
    if (!viewer) {
      console.error('viewer 不可用');
      return null;
    }

    if (currentPoints.value.length < 2) {
      console.log('点数不足，无法完成绘制');
      return null;
    }

    // 防止重复调用
    if (!isDrawing.value) {
      return null;
    }

    isDrawing.value = false;

    // 移除绘制时的临时实体
    if (drawingEntity.value) {
      viewer.entities.remove(drawingEntity.value);
      drawingEntity.value = null;
    }

    const pipeData: PipeData = {
      points: [...currentPoints.value],
      material: {
        material: 'PE',
        diameter: 110,
        pressure: 0.4,
        thickness: 10,
        coating: '防腐涂层'
      },
      id: generateId()
    };

    // 绘制最终的管线
    drawFinalPipe(pipeData);

    // 清除临时点标记
    currentPointEntities.value.forEach((entity) => {
      viewer.entities.remove(entity);
    });
    currentPointEntities.value = [];

    // 销毁事件处理器
    if (handler.value) {
      handler.value.destroy();
      handler.value = null;
    }

    currentPoints.value = [];

    // 通知外部绘制完成
    if (onDrawingComplete) {
      onDrawingComplete(pipeData);
    }

    return pipeData;
  };

  // 绘制最终的管线
  const drawFinalPipe = (pipeData: PipeData) => {
    const viewer = viewerRef.value;
    if (!viewer) {
      console.error('viewer 不可用');
      return;
    }

    const positions = pipeData.points.map((point) => Cartesian3.fromDegrees(point.longitude, point.latitude, point.height || 0));

    viewer.entities.add({
      id: pipeData.id,
      polyline: {
        positions: positions,
        width: 6,
        material: Color.YELLOW, // 用户绘制的管线使用黄色
        clampToGround: true
      }
    });
  };

  // 停止绘制
  const stopDrawing = () => {
    const viewer = viewerRef.value;
    if (!viewer) {
      console.error('viewer 不可用');
      return;
    }

    console.log('=== 停止绘制 ===');
    isDrawing.value = false;
    currentPoints.value = [];

    // 清除当前正在绘制的临时实体
    if (drawingEntity.value) {
      viewer.entities.remove(drawingEntity.value);
      drawingEntity.value = null;
    }

    // 清除当前绘制的临时点标记
    currentPointEntities.value.forEach((entity) => {
      viewer.entities.remove(entity);
    });
    currentPointEntities.value = [];

    // 销毁事件处理器
    if (handler.value) {
      handler.value.destroy();
      handler.value = null;
      console.log('绘制事件处理器已销毁');
    }
  };

  // 撤销最后一个点
  const undoLastPoint = () => {
    const viewer = viewerRef.value;
    if (!viewer) {
      console.error('viewer 不可用');
      return;
    }

    if (currentPoints.value.length === 0) return;

    // 移除最后一个点
    currentPoints.value.pop();

    // 移除最后一个点实体
    if (currentPointEntities.value.length > 0) {
      const lastEntity = currentPointEntities.value.pop();
      if (lastEntity) {
        viewer.entities.remove(lastEntity);
      }
    }

    // 通知外部点数变化
    if (onPointAdded) {
      onPointAdded([...currentPoints.value]);
    }

    // 重新绘制线段
    if (currentPoints.value.length >= 2) {
      drawPolyline();
    } else if (drawingEntity.value) {
      viewer.entities.remove(drawingEntity.value);
      drawingEntity.value = null;
    }
  };

  // 清除所有管线
  const clearAllPipes = () => {
    const viewer = viewerRef.value;
    if (!viewer) {
      console.error('viewer 不可用');
      return;
    }

    try {
      // 清除当前绘制状态
      isDrawing.value = false;
      currentPoints.value = [];

      // 清除事件处理器
      if (handler.value) {
        handler.value.destroy();
        handler.value = null;
      }

      // 清除风险信息悬停相关资源
      if (currentRiskHandler) {
        currentRiskHandler.destroy();
        currentRiskHandler = null;
      }
      if (currentTooltipEntity) {
        viewer.entities.remove(currentTooltipEntity);
        currentTooltipEntity = null;
      }

      // 移除当前绘制的临时实体
      if (drawingEntity.value) {
        viewer.entities.remove(drawingEntity.value);
        drawingEntity.value = null;
      }

      // 移除当前绘制的临时点标记
      currentPointEntities.value.forEach((entity) => {
        viewer.entities.remove(entity);
      });
      currentPointEntities.value = [];

      // 移除所有管线相关的实体
      const entitiesToRemove: Entity[] = [];
      const entities = Array.from(viewer.entities.values);

      entities.forEach((entity) => {
        if (
          entity.id &&
          typeof entity.id === 'string' &&
          (entity.id.startsWith('pipe_') || entity.id.endsWith('_label') || entity.id.startsWith('distance_'))
        ) {
          entitiesToRemove.push(entity);
        }
      });

      // 批量移除实体
      entitiesToRemove.forEach((entity) => {
        try {
          viewer.entities.remove(entity);
        } catch (error) {
          console.warn('移除实体失败:', error);
        }
      });

      // 强制更新场景
      viewer.scene.requestRender();
    } catch (error) {
      console.error('清除管线失败:', error);
    }
  };

  // 生成唯一ID
  const generateId = (): string => {
    return `pipe_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  };

  // 计算两点间距离
  const calculateDistance = (point1: PipePoint, point2: PipePoint): number => {
    const pos1 = Cartesian3.fromDegrees(point1.longitude, point1.latitude);
    const pos2 = Cartesian3.fromDegrees(point2.longitude, point2.latitude);
    return Cartesian3.distance(pos1, pos2);
  };

  // 计算管线总长度
  const calculatePipeLength = (points: PipePoint[]): number => {
    let totalLength = 0;
    for (let i = 0; i < points.length - 1; i++) {
      totalLength += calculateDistance(points[i], points[i + 1]);
    }
    return totalLength;
  };
  // 检查两个线段是否相交
  const doSegmentsIntersect = (p1: PipePoint, p2: PipePoint, p3: PipePoint, p4: PipePoint): boolean => {
    const scale = 111000; // 1度约等于111公里
    const x1 = p1.longitude * scale;
    const y1 = p1.latitude * scale;
    const x2 = p2.longitude * scale;
    const y2 = p2.latitude * scale;
    const x3 = p3.longitude * scale;
    const y3 = p3.latitude * scale;
    const x4 = p4.longitude * scale;
    const y4 = p4.latitude * scale;

    // 计算分母
    const denominator = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
    if (denominator === 0) {
      return false;
    }

    // 计算参数 t 和 u
    const ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator;
    const ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator;

    // 检查参数是否在 [0,1] 范围内
    return ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1;
  };

  // 计算两条管线之间的最短距离
  const computeMinDistance = (userPipeline: PipePoint[], targetPipelines: number[][]) => {
    if (!userPipeline || userPipeline.length === 0 || !targetPipelines || targetPipelines.length === 0) {
      console.warn('管线数据为空');
      return {
        distance: Number.MAX_VALUE,
        points: {
          userPoint: null,
          targetPoint: null
        },
        lineCoordinates: {
          start: null,
          end: null
        }
      };
    }

    let minDistance = Number.MAX_VALUE;
    let closestUserPoint: PipePoint | null = null;
    let closestTargetCoord: number[] | null = null;
    let hasIntersection = false;

    // 遍历用户管线的每个线段
    for (let i = 0; i < userPipeline.length - 1; i++) {
      const userSegStart = userPipeline[i];
      const userSegEnd = userPipeline[i + 1];

      // 遍历目标管线的每个线段
      for (let j = 0; j < targetPipelines.length - 1; j++) {
        const targetSegStart = {
          longitude: targetPipelines[j][0],
          latitude: targetPipelines[j][1],
          height: targetPipelines[j][2] || 0
        };
        const targetSegEnd = {
          longitude: targetPipelines[j + 1][0],
          latitude: targetPipelines[j + 1][1],
          height: targetPipelines[j + 1][2] || 0
        };

        // 检查是否相交
        if (doSegmentsIntersect(userSegStart, userSegEnd, targetSegStart, targetSegEnd)) {
          hasIntersection = true;
          break;
        }

        // 如果没有相交，计算最短距离
        const distance = computeSegmentDistance(userSegStart, userSegEnd, targetSegStart, targetSegEnd);

        if (distance.distance < minDistance) {
          minDistance = distance.distance;
          closestUserPoint = distance.point1;
          closestTargetCoord = [distance.point2.longitude, distance.point2.latitude, distance.point2.height];
        }
      }

      if (hasIntersection) {
        break;
      }
    }

    // 如果有相交，返回特殊值表示相交
    if (hasIntersection) {
      return {
        distance: 0,
        intersects: true,
        points: {
          userPoint: null,
          targetPoint: null
        },
        lineCoordinates: {
          start: null,
          end: null
        }
      };
    }

    // 只有在找到最近点且没有相交时才进行精确的 Cartesian3 转换
    if (closestUserPoint && closestTargetCoord) {
      const userPos = Cartesian3.fromDegrees(closestUserPoint.longitude, closestUserPoint.latitude, closestUserPoint.height || 0);
      const targetPos = Cartesian3.fromDegrees(closestTargetCoord[0], closestTargetCoord[1], closestTargetCoord[2] || 0);

      // 计算精确距离
      const exactDistance = Cartesian3.distance(userPos, targetPos);

      return {
        distance: exactDistance,
        intersects: false,
        points: {
          userPoint: userPos,
          targetPoint: targetPos
        },
        lineCoordinates: {
          start: {
            longitude: closestUserPoint.longitude,
            latitude: closestUserPoint.latitude,
            height: closestUserPoint.height || 0
          },
          end: {
            longitude: closestTargetCoord[0],
            latitude: closestTargetCoord[1],
            height: closestTargetCoord[2] || 0
          }
        }
      };
    }

    return {
      distance: Number.MAX_VALUE,
      points: {
        userPoint: null,
        targetPoint: null
      },
      lineCoordinates: {
        start: null,
        end: null
      }
    };
  };

  // 计算两个线段之间的最短距离
  const computeSegmentDistance = (p1: PipePoint, p2: PipePoint, p3: PipePoint, p4: PipePoint) => {
    // 将经纬度转换为平面坐标（近似计算）
    const scale = 111000; // 1度约等于111公里
    const x1 = p1.longitude * scale;
    const y1 = p1.latitude * scale;
    const x2 = p2.longitude * scale;
    const y2 = p2.latitude * scale;
    const x3 = p3.longitude * scale;
    const y3 = p3.latitude * scale;
    const x4 = p4.longitude * scale;
    const y4 = p4.latitude * scale;

    // 线段向量
    const ux = x2 - x1;
    const uy = y2 - y1;
    const vx = x4 - x3;
    const vy = y4 - y3;

    // 线段长度的平方
    const lu = ux * ux + uy * uy;
    const lv = vx * vx + vy * vy;

    // 如果任一线段长度为0，则退化为点到线段的距离
    if (lu < 1e-10 || lv < 1e-10) {
      return computePointSegmentDistance(p1, p3, p4);
    }

    // 计算投影参数
    const wx = x1 - x3;
    const wy = y1 - y3;
    const t = -(wx * ux + wy * uy) / lu;
    const s = -(wx * vx + wy * vy) / lv;

    // 根据投影参数计算最近点
    let point1: PipePoint, point2: PipePoint;

    if (t <= 0) {
      point1 = p1;
    } else if (t >= 1) {
      point1 = p2;
    } else {
      point1 = {
        longitude: p1.longitude + t * (p2.longitude - p1.longitude),
        latitude: p1.latitude + t * (p2.latitude - p1.latitude),
        height: (p1.height || 0) + t * ((p2.height || 0) - (p1.height || 0))
      };
    }

    if (s <= 0) {
      point2 = p3;
    } else if (s >= 1) {
      point2 = p4;
    } else {
      point2 = {
        longitude: p3.longitude + s * (p4.longitude - p3.longitude),
        latitude: p3.latitude + s * (p4.latitude - p3.latitude),
        height: (p3.height || 0) + s * ((p4.height || 0) - (p3.height || 0))
      };
    }

    // 计算最短距离
    const dx = (point2.longitude - point1.longitude) * scale;
    const dy = (point2.latitude - point1.latitude) * scale;
    const distance = Math.sqrt(dx * dx + dy * dy);

    return {
      distance,
      point1,
      point2
    };
  };

  // 计算点到线段的最短距离
  const computePointSegmentDistance = (point: PipePoint, segStart: PipePoint, segEnd: PipePoint) => {
    const scale = 111000;
    const x = point.longitude * scale;
    const y = point.latitude * scale;
    const x1 = segStart.longitude * scale;
    const y1 = segStart.latitude * scale;
    const x2 = segEnd.longitude * scale;
    const y2 = segEnd.latitude * scale;

    const A = x - x1;
    const B = y - y1;
    const C = x2 - x1;
    const D = y2 - y1;

    const dot = A * C + B * D;
    const lenSq = C * C + D * D;
    let param = -1;

    if (lenSq !== 0) {
      param = dot / lenSq;
    }

    let point2: PipePoint;

    if (param < 0) {
      point2 = segStart;
    } else if (param > 1) {
      point2 = segEnd;
    } else {
      point2 = {
        longitude: segStart.longitude + param * (segEnd.longitude - segStart.longitude),
        latitude: segStart.latitude + param * (segEnd.latitude - segStart.latitude),
        height: (segStart.height || 0) + param * ((segEnd.height || 0) - (segStart.height || 0))
      };
    }

    const dx = (point2.longitude - point.longitude) * scale;
    const dy = (point2.latitude - point.latitude) * scale;
    const distance = Math.sqrt(dx * dx + dy * dy);

    return {
      distance,
      point1: point,
      point2
    };
  };

  // 组件卸载时清理
  onUnmounted(() => {
    if (handler.value) {
      handler.value.destroy();
      handler.value = null;
    }

    // 清理风险信息悬停相关的资源
    if (currentRiskHandler) {
      currentRiskHandler.destroy();
      currentRiskHandler = null;
    }
    if (currentTooltipEntity && viewerRef.value) {
      viewerRef.value.entities.remove(currentTooltipEntity);
      currentTooltipEntity = null;
    }
  });

  // 从管线数据绘制管线
  const drawPipeFromData = (pipeData: PipeData, color: Color = Color.BLUE) => {
    const viewer = viewerRef.value;
    if (!viewer) {
      console.error('viewer 不可用');
      return;
    }

    const positions = pipeData.points.map((point) => Cartesian3.fromDegrees(point.longitude, point.latitude, point.height || 0));

    // 绘制管线
    viewer.entities.add({
      id: pipeData.id,
      name: pipeData.type || '管线',
      polyline: {
        positions: positions,
        width: 6,
        material: color,
        clampToGround: true
      }
    });
  };

  // 解析几何坐标字符串
  const parseGeometryString = (geometryString: string): number[][] => {
    try {
      const cleanString = geometryString.replace(/,$/, '');
      const coords = cleanString.split(',').map((coord) => parseFloat(coord.trim()));

      const coordinates: number[][] = [];
      for (let i = 0; i < coords.length; i += 2) {
        if (i + 1 < coords.length) {
          coordinates.push([coords[i], coords[i + 1], 0]);
        }
      }

      return coordinates;
    } catch (error) {
      console.error('解析坐标字符串失败:', error);
      return [];
    }
  };

  // 从响应数据加载管线
  const loadPipesFromResponse = async (responseData: any) => {
    try {
      if (!responseData || !Array.isArray(responseData)) {
        console.warn('响应数据格式不正确，期望数组格式');
        return;
      }

      // 处理单个数据项
      const processDataItem = async (dataItem: any) => {
        const setVo = dataItem.setVo;
        if (!dataItem.content || !Array.isArray(dataItem.content)) return;

        // 判断是否是热力管线
        const isHeatPipe = setVo?.name?.includes('热力') || false;

        if (isHeatPipe) {
          // 热力管线：保持每段管线独立，但只显示一个标签
          let minDistanceToUser = Number.MAX_VALUE;
          let closestLineCoordinates = null;
          let firstPipeDrawn = false;

          for (const pipeItem of dataItem.content) {
            if (!pipeItem.geometry) continue;

            const coordinates = parseGeometryString(pipeItem.geometry);
            if (!coordinates || coordinates.length < 2) continue;

            const pipePoints: PipePoint[] = coordinates.map((coord) => ({
              longitude: coord[0],
              latitude: coord[1],
              height: coord[2] || 0
            }));

            const pipeData: PipeData = {
              points: pipePoints,
              material: {
                material: 'PE',
                diameter: 110,
                pressure: 0.4,
                thickness: 10,
                coating: '防腐涂层'
              },
              id: `pipe_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
              type: setVo?.name || '热力管线'
            };

            // 绘制热力管线（绿色）
            drawPipeFromData(pipeData, Color.LIME);
            firstPipeDrawn = true;

            // 计算与用户管线的距离，但只保留最短的
            if (getUserDrawnPipe) {
              const userDrawnPipe = getUserDrawnPipe();
              if (userDrawnPipe) {
                const userPipeCoordinates = userDrawnPipe.points.map((point) => [point.longitude, point.latitude, point.height || 0]);
                const distance = computeMinDistance(pipeData.points, userPipeCoordinates);

                // 如果管线相交，不显示距离线
                if (distance.intersects) {
                  console.log('管线相交，不显示距离线');
                  break;
                }

                if (distance.distance < minDistanceToUser) {
                  minDistanceToUser = distance.distance;
                  closestLineCoordinates = distance.lineCoordinates;
                }
              }
            }
          }

          // 只在找到最短距离时绘制距离线
          if (minDistanceToUser < Number.MAX_VALUE && closestLineCoordinates?.start && closestLineCoordinates?.end) {
            drawDistanceLine(closestLineCoordinates, minDistanceToUser);
          }
        } else {
          // 轨交数据：保持原样，每段分别绘制
          for (const pipeItem of dataItem.content) {
            if (!pipeItem.geometry || !pipeItem.objectId) continue;

            const coordinates = parseGeometryString(pipeItem.geometry);
            if (!coordinates || coordinates.length < 2) continue;

            const pipePoints: PipePoint[] = coordinates.map((coord) => ({
              longitude: coord[0],
              latitude: coord[1],
              height: coord[2] || 0
            }));

            const pipeData: PipeData = {
              points: pipePoints,
              material: {
                material: 'PE',
                diameter: 110,
                pressure: 0.4,
                thickness: 10,
                coating: '防腐涂层'
              },
              id: `pipe_${pipeItem.objectId}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
              type: setVo?.name || '轨道交通'
            };

            // 绘制轨交管线（蓝色）
            drawPipeFromData(pipeData, Color.BLUE);

            // 如果有用户绘制的管线，计算与用户绘制管线的距离
            if (getUserDrawnPipe) {
              const userDrawnPipe = getUserDrawnPipe();
              if (userDrawnPipe) {
                const userPipeCoordinates = userDrawnPipe.points.map((point) => [point.longitude, point.latitude, point.height || 0]);
                const minDistance = computeMinDistance(pipeData.points, userPipeCoordinates);

                // 只在管线不相交时显示距离线
                if (
                  !minDistance.intersects &&
                  minDistance.distance < Number.MAX_VALUE &&
                  minDistance.lineCoordinates.start &&
                  minDistance.lineCoordinates.end
                ) {
                  drawDistanceLine(minDistance.lineCoordinates, minDistance.distance);
                }
              }
            }
          }
        }
      };

      // 遍历数据
      for (const item of responseData) {
        await processDataItem(item);
      }

      ElMessage.success('管线数据加载完成');
    } catch (error) {
      console.error('加载管线数据失败:', error);
      throw error;
    }
  };

  // 存储当前的风险信息悬停处理器和实体
  let currentRiskHandler: ScreenSpaceEventHandler | null = null;
  let currentTooltipEntity: Entity | null = null;

  // 为管线添加风险信息悬停功能
  const addRiskInfoHover = async (pipeData: PipeData, riskInfo: PipeRiskInfo) => {
    const viewer = viewerRef.value;
    if (!viewer) return;

    // 确保风险等级字典已初始化
    await initRiskLevelDict();

    // 清除之前的处理器和实体
    if (currentRiskHandler) {
      currentRiskHandler.destroy();
      currentRiskHandler = null;
    }
    if (currentTooltipEntity) {
      viewer.entities.remove(currentTooltipEntity);
      currentTooltipEntity = null;
    }

    // 创建新的事件处理器
    currentRiskHandler = new ScreenSpaceEventHandler(viewer.scene.canvas);

    // 添加鼠标移动事件监听
    currentRiskHandler.setInputAction((event: any) => {
      const pickedObject = viewer.scene.pick(event.endPosition);

      if (viewer.scene.pickPositionSupported && pickedObject && pickedObject.id) {
        const cartesian = viewer.scene.pickPosition(event.endPosition);

        if (cartesian) {
          const entity = pickedObject.id;

          // 获取实体ID和名称
          let entityId = '';
          let entityName = '';

          if (entity.id && typeof entity.id === 'string') {
            entityId = entity.id;
          }
          if (entity.name && typeof entity.name === 'string') {
            entityName = entity.name;
          }

          // 检查是否是目标管线或其标签
          const isPipeEntity =
            entityId === pipeData.id ||
            entityId.startsWith(`${pipeData.id}_`) ||
            (pipeData.type && (entityName === pipeData.type || entityName.startsWith(`${pipeData.type}_`)));

          if (isPipeEntity) {
            // 如果提示实体不存在，创建一个新的
            if (!currentTooltipEntity) {
              currentTooltipEntity = viewer.entities.add({
                position: cartesian,
                label: {
                  text: `风险等级: ${formatRiskLevel(riskInfo.level)}\n风险总分: ${riskInfo.value}\n管道自身: ${riskInfo.rqzs}\n第三方损害: ${riskInfo.dsfsh}\n其他因素: ${riskInfo.qtys}\n处置建议: ${riskInfo.czjy}`,
                  font: '14px sans-serif',
                  fillColor: Color.WHITE,
                  outlineColor: Color.BLACK,
                  outlineWidth: 2,
                  style: LabelStyle.FILL_AND_OUTLINE,
                  verticalOrigin: VerticalOrigin.TOP,
                  horizontalOrigin: HorizontalOrigin.LEFT,
                  pixelOffset: new Cartesian2(10, 10),
                  showBackground: true,
                  backgroundColor: new Color(0, 0, 0, 0.7),
                  backgroundPadding: new Cartesian2(7, 7),
                  disableDepthTestDistance: Number.POSITIVE_INFINITY
                }
              });
            } else {
              // 更新提示实体的位置
              (currentTooltipEntity.position as any) = cartesian;
            }
          } else if (currentTooltipEntity) {
            // 如果鼠标移出管线，移除提示实体
            viewer.entities.remove(currentTooltipEntity);
            currentTooltipEntity = null;
          }
        }
      } else if (currentTooltipEntity) {
        // 如果鼠标没有选中任何对象，移除提示实体
        viewer.entities.remove(currentTooltipEntity);
        currentTooltipEntity = null;
      }
    }, ScreenSpaceEventType.MOUSE_MOVE);
  };

  // 绘制距离连线
  const drawDistanceLine = (
    lineCoordinates: {
      start: { longitude: number; latitude: number; height?: number };
      end: { longitude: number; latitude: number; height?: number };
    },
    distance: number
  ) => {
    const viewer = viewerRef.value;
    if (!viewer) {
      console.error('viewer 不可用');
      return;
    }

    const startHeight = lineCoordinates.start.height || 0;
    const endHeight = lineCoordinates.end.height || 0;

    const startPos = Cartesian3.fromDegrees(lineCoordinates.start.longitude, lineCoordinates.start.latitude, startHeight);
    const endPos = Cartesian3.fromDegrees(lineCoordinates.end.longitude, lineCoordinates.end.latitude, endHeight);

    const timestamp = Date.now();
    const randomSuffix = Math.random().toString(36).substr(2, 9);
    const uniqueId = `${timestamp}_${randomSuffix}`;

    // 绘制连线
    viewer.entities.add({
      id: `distance_line_${uniqueId}`,
      polyline: {
        positions: [startPos, endPos],
        width: 5,
        material: Color.RED,
        clampToGround: false
      }
    });

    // 添加端点
    viewer.entities.add({
      id: `distance_start_dot_${uniqueId}`,
      position: startPos,
      point: {
        pixelSize: 8,
        color: Color.RED,
        outlineColor: Color.WHITE,
        outlineWidth: 2
      }
    });

    viewer.entities.add({
      id: `distance_end_dot_${uniqueId}`,
      position: endPos,
      point: {
        pixelSize: 8,
        color: Color.RED,
        outlineColor: Color.WHITE,
        outlineWidth: 2
      }
    });

    // 添加距离标签
    const midPoint = Cartesian3.lerp(startPos, endPos, 0.5, new Cartesian3());
    viewer.entities.add({
      id: `distance_label_${uniqueId}`,
      position: midPoint,
      label: {
        text: `${distance.toFixed(2)}米`,
        font: '24px Arial',
        style: 2,
        outlineWidth: 3,
        verticalOrigin: 0,
        pixelOffset: new Cartesian3(0, 0),
        fillColor: Color.YELLOW,
        outlineColor: Color.BLACK,
        showBackground: true,
        backgroundColor: Color.BLACK.withAlpha(0.9),
        backgroundPadding: new Cartesian3(15, 8)
      }
    });
  };

  return {
    isDrawing,
    currentPoints,
    startDrawing,
    stopDrawing,
    finishDrawing,
    undoLastPoint,
    clearAllPipes,
    calculateDistance,
    calculatePipeLength,
    computeMinDistance,
    drawPipeFromData,
    parseGeometryString,
    loadPipesFromResponse,
    addRiskInfoHover,
    drawDistanceLine
  };
};

export default usePipeDrawing;
